<?php

class Application_Model_User extends Application_Model_DomainObject {

    protected $_id;
    protected $_email;
    protected $_phone;
    protected $_nikename;
    protected $_realname;
    protected $_datecreated;
    protected $_password;
    protected $_passwordsalt;
    protected $_username;
    protected $_userLevel;
    protected $_lastLogin;
    protected $_synKey;
    protected $_userType;
    protected $_pic;
    protected $_state;
    protected $_logintimes;
    protected $_loginip;
    protected $_storeno;
    protected $_remark;
    protected $_locationtime;
    protected $_source;
    protected $_bindId;
    protected $_recommendId;
    protected $_cityId;

    /**
     * 新用户 
     */
    const STATUS_New = 0;

    /**
     * 邮箱已经验证 
     */
    const STATUS_Email = 1;

    public function getnikename() {
        return htmlspecialchars($this->_nikename);
    }

    public function getrealname() {
        return htmlspecialchars($this->_realname);
    }

    public function getcityname() {
        if ($this->_cityId != null) {
            $where = array();
            $where[' id = '] = $this->_cityId;
            $getItem = new Application_Model_DbTable_city();
            return $getItem->queryOne($where);
        }
    }

    public function getPicFile() {
        if ($this->_pic) {
            $userid = str_pad($this->_id, 9, '0', STR_PAD_LEFT);
            return '/data/avatar/' . substr($userid, 0, 3) . '/' . substr($userid, 3, 2) . '/' . substr($userid, 5, 2) . '/' . $this->_pic;
        } else {
            return '/data/avatar/00.png';
        }
    }

    public static function current() {
        return Application_Model_User::getByEmail(Uuch_BaseController::getCurrentUserName());
    }

    public function getLevel() {
        return $this->userLevel;
    }

    /**
     * 生成密码
     * @param string $password
     * @param string $passwordSalt
     * @return string
     */
    public function generatePassword($password, $passwordsalt) {
        return md5(md5($password) . $passwordsalt);
    }

    /**
     * 根据email返回用户
     * @param string $email
     * @return Application_Model_User
     */
    public static function getByEmail($email) {
        $db = new Application_Model_DbTable_User();
        return $db->queryOne(array('email' => $email));
    }

    public static function getByUserId($id) {
        $db = new Application_Model_DbTable_User();
        return $db->queryOne(array('id' => $id));
    }

    /**
     * 返回联合登录用户
     * @param type $synKey
     * @return Application_Model_User
     */
    public static function getByKey($synKey) {
        $db = new Application_Model_DbTable_User();
        return $db->queryOne(array('synKey' => $synKey));
    }

    /*
     * 获取用户总数
     */

    public static function getItemCount() {
        $db = new Application_Model_DbTable_User();
        return $db->getItemCount();
    }

    /**
     * 根据用户名
     * @param string $username
     * @return Application_Model_User
     */
    public static function getbyusername($username) {
        $db = new Application_Model_DbTable_User();
        return $db->queryOne(array('username' => $username));
    }

    /**
     * 根据用户名
     * @param string $nikename
     * @return Application_Model_User
     */
    public static function getbynikename($nikename) {
        $db = new Application_Model_DbTable_User();
        return $db->queryOne(array('nikename' => $nikename));
    }

    private $_account;

    /**
     * 返回用户的帐号
     * @return Application_Model_UserAccount 
     */
    public function getAccount() {
        if ($this->_account == NULL) {
            $this->_account = Application_Model_UserAccount::getByUserId($this->Id);
            if ($this->_account == NULL) {
                $account = new Application_Model_UserAccount(array('id' => $this->Id, 'money' => 0, 'score' => 0, 'userGrade' => 0, 'birthday' => 0, 'gradePrivilege' => 0));
                $account->insertId();
                $this->_account = $account;
            }
        }
        return $this->_account;
    }

    private $_profile;

    /**
     * 返回当前用户的个人信息
     * @return Application_Model_Profile 
     */
    public function getProfile() {
        if ($this->_profile == NULL) {
            $this->_profile = Application_Model_Profile::getByUserId($this->Id);
        }
        return $this->_profile;
    }

    /**
     * 返回当前用户的等级
     */
    public function getLevelText() {
        $accountItem = Application_Model_UserAccount::addAccount($this->_id);
        $arrGrade = Application_Model_UserAccount::getUserGradeAll();
        return $arrGrade[$accountItem->UserGrade];
    }

//    /**
//     * 返回用户的仓库号
//     */
//    public function getStoreNo(){
//    	return Uuch_Util::getShortNum($this->Id, 4);
//    }

    private $_coupons;

    /**
     * 返回当前用户的所有可用优惠券
     * @return type 
     */
    public function getCoupons() {
        if ($this->_coupons == NULL) {
            $this->_coupons = Application_Model_Coupon::getByUser($this->_id, Application_Model_Coupon::STATUS_OK);
        }
        return $this->_coupons;
    }

    public static function getByStoreNo($storeno) {
        $firstLetter = substr($storeno, 0, 1);
        if (strtoupper($firstLetter) == "F") {
            $storeno = "P" . strtoupper(substr($storeno, 1, 5));
        }
        return Application_Model_User::getDao()->queryOne(array('storeno' => $storeno));
    }

    public static function search() {
        return self::getDao()->queryPage(array('storeno' => 'P0002'));
    }

    public static function getcountuser() {
        $where['datecreated >='] = date('Y-m-d');
        $result = Application_Model_User::getDao()->count($where);
        return $result;
    }

    public static function getloginuser() {
        $where['lastLogin >='] = date('Y-m-d');
        $result = Application_Model_User::getDao()->count($where);
        return $result;
    }

    public static function getselcount($userSearch, $pagesize, $pageindex) {
        if ($userSearch->getSearchFileds() == null) {
            return null;
        } else {
//            var_dump($userSearch->getSearchFileds());echo "<br>";var_dump($userSearch->getOrderBy());
            return Application_Model_User::getDao()->queryPage($userSearch->getSearchFileds(), $userSearch->getOrderBy(), $pagesize, $pageindex);
        }
    }

    /**
     * 获取用户成长值
     */
    public function getbyscore() {
        $userid = $this->_id;
        $where['id = '] = $userid;
        $accountDb = new Application_Model_DbTable_UserAccount();
        $result = $accountDb->queryOne($where);
        return $result;
    }

    public static function editmoney($userid, $editMoney, $reason, $message, $operate, $vstitle = null) {
        $userItem = Application_Model_UserAccount::load($userid);
        if ($userItem) {
            $content = '';
            $adddesc = '';
            $money = round($editMoney, 2);
            $beforeMoney = $userItem->money;
           // $re = 2;
            if ($operate == "recharge") { //充值
                if(is_numeric($vstitle)){
                    $billall = Application_Model_wayBillItem::load($vstitle);
                    if(!empty($billall)){
                        $adddesc = '(运单号:' . $billall->billNo . ')';
                    }
                }
                $userItem->money = $userItem->money + $money;
                $title = "手工充值：" . $money;
                $content = "于" . date("Y-m-d H:i:s") . " 悠奇工作人员手工充值：" . $money . "(元)原因为：" . $reason;
                $re = 3;
                Application_Model_Operate::addOperate($money, null, $vstitle, "会员手工充值" . $adddesc, $userItem->id);
                if ($message == "message") {
                    Application_Model_Operate::addOperate(0, null, $userItem->id, "会员手工充值发送站内信", $userItem->id);
                }
            } else if ($operate == "deduct") {//扣款
                if(is_numeric($vstitle)){
                    $billall = Application_Model_wayBillItem::load($vstitle);
                    if(!empty($billall)){
                        $adddesc = '(运单号:' . $billall->billNo . ')';
                    }
                }
                $userItem->money = $userItem->money - $money;
                $title = "手工扣款：" . $money;
                $content = "于" . date("Y-m-d H:i:s") . "悠奇工作人员手工扣款：" . $money . "(元)原因为：" . $reason;
                $re = 4;
                Application_Model_Operate::addOperate($money, null, $vstitle, "会员手工扣款" . $adddesc, $userItem->id);
                if ($message == "message") {
                    Application_Model_Operate::addOperate(0, null, $userItem->id, "会员手工扣款发送站内信", $userItem->id);
                }
            } else if ($operate == "refund") {// 上门取件取消退款
                $userItem->money = $userItem->money + $money;
                $title = $vstitle;
                $content = "于" . date("Y-m-d H:i:s") . " 系统自动退款：" . $money . "(元)原因为：" . $reason;
                $re = 5;
                Application_Model_Operate::addOperate($money, null, $title, "系统给上门取件(" . $title . ")退款", $userItem->id);
                if ($message == "message") {
                    Application_Model_Operate::addOperate(0, null, $title, "系统给上门取件(" . $title . ")退款发送站内信", $userItem->id);
                }
            } else if ($operate == "jiesuan") { //上门取件结算
                $title = "上门取件" . $vstitle . "结算";
                if ($money > 0) {
                    $userItem->money = $userItem->money + $money;
                    $content = "于" . date("Y-m-d H:i:s") . " 系统自动退款：" . $money . "(元)原因为：" . $reason;
                } else if ($money == 0) {
                    $content = "于" . date("Y-m-d H:i:s") . "系统结算原因为：预付款与国内运费一致";
                }
                $re = 6;
                Application_Model_Operate::addOperate($money, null, $vstitle, "系统给上门取件(" . $vstitle . ")结算", $userItem->id);
                if ($message == "message") {
                    Application_Model_Operate::addOperate(0, null, $vstitle, "系统给上门取件(" . $vstitle . ")结算发送站内信", $userItem->id);
                }
            }
           // if ($re > 2) {
                $afterMoney = $userItem->money;
                $userItem->save();
                $history = new Application_Model_UserAccountHistory();
                if ($operate == "jiesuan") {
                    $history->type = Application_Model_UserAccountHistory::TYPE_VISIT;
                } else {
                    $history->type = Application_Model_UserAccountHistory::TYPE_MANU;
                }
                $history->beforeMoney = $beforeMoney;
                $history->afterMoney = $afterMoney;
                $history->comment = $reason;
                $history->dateCreated = date("Y-m-d H:i:s");
                $history->relaseId = "1";
                $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
                $history->accountId = $userid;
                $history->save();
                if ($message == "message") {
                    $messageItem = new Application_Model_Mail();
                    $messageItem->title = $title;
                    $messageItem->userId = $userid;
                    $messageItem->type = 2;
                    $messageItem->status = 0;
                    $messageItem->message = $content;
                    $messageItem->dateCreated = date("Y-m-d H:i:s");
                    $messageItem->save();
                }
           // }
            return $re;
        } else {
            return 2;
        }
    }

    //根据仓库号获取用户信息
    public static function bystore($storeno) {
        $where[' storeno = '] = $storeno;
        return Application_Model_User::getDao()->queryOne($where);
    }

    /*
     * 根据ip获取对应国家
     */

    public function getbyip() {
        $ipDb = new Application_Model_ip();
        $ip = $this->_loginip;
        $result = $ipDb->convertip($ip);
        $result = iconv("GBK", "UTF-8", $result);
        if (!($this->_cityId > 0)) {
            $cityItem = Application_Model_city::getByName($result);
            if ($cityItem) {
                $this->_cityId = $cityItem->id;
            } else {
                $this->_cityId = 10000;
            }
            $this->save();
        }
        return $result;
    }

//    public function getCityName()
//    {
//        if($this->_cityId)
//            return Application_Model_city::load($this->_cityId)->Name;
//        return null;
//    }

    public function byStoreLocation() {
        $result = Application_Model_StoreLocation::getUserAll($this->_id);
        if (!$result) {
//            $locationItem = Application_Model_StoreLocation::getDao()->queryOne(array("status"=>0));
//            if($locationItem){
//                $locationItem->userId = $this->_id;
//                $locationItem->status = 1;
//                $locationItem->save();
//                $result = Application_Model_StoreLocation::getUserAll($this->_id);
//            }else{
            return 0;
//            }
        }
        foreach ($result as $value) {
            $arrre[] = $value->locationNo;
        }
        return $arrre;
    }

    public function getUserDetail($id, $nikename = null, $storeno = null) {
        $getItem = new Application_Model_DbTable_User();
        $where['id = '] = $id;
        $and = ' and ';
        if ($nikename != '') {
            $where[$and . ' nikename like '] = '%' . $nikename . '%';
        }
        if ($storeno != '') {
            $where[$and . ' storeno like '] = '%' . $storeno . '%';
        }
        return $getItem->queryOne($where);
    }

    public function editUserDetail($id, $realname, $nikename, $uemail, $score, $profile_set) {
        if ($id != '') {
            $userDetail = Application_Model_User::load($id);
            $userDetail->realname = $realname;
            $userDetail->nikename = $nikename;
            $userDetail->email = $uemail;
            $userDetail->save();
            $accountDetail = Application_Model_UserAccount::load($id);
            if ($accountDetail == null) {
                $accountDetail = new Application_Model_UserAccount();
            }
            $accountDetail->score = (int) $score;
            $accountDetail->save();

            $profileDetail = Application_Model_Profile::getByUserId($id);
            if ($profileDetail == null) {
                $profileDetail = new Application_Model_Profile();
            }
            $profileDetail->userId = $id;
            foreach ($profile_set as $key => $v) {
                $profileDetail->$key = $v;
            }
            Application_Model_Operate::addOperate(0, null, $id, "修改用户信息", $id);
            $profileDetail->save();
            return true;
        } else {
            return false;
        }
    }

    public static function getByNikeNameStore($quick) {
        $where[" nikename like "] = "%" . $quick . "%";
        $firstLetter = substr($quick, 0, 1);
        if (strtoupper($firstLetter) == "F") {
            $storeno = "P" . strtoupper(substr($quick, 1, 5));
        } else {
            $storeno = $quick;
        }
        $where[" or storeno = "] = $storeno;
        return Application_Model_User::getDao()->queryAll($where);
    }

    protected $_bindUser;

    /**
     * 返回对应的绑定用户
     * @return Application_Model_User
     */
    public function getBindUser() {
        if ($this->_bindUser == null && $this->_bindId) {
            $this->_bindUser = Application_Model_User::load($this->_bindId);
        }
        return $this->_bindUser;
    }

    public static function getByRecommendId($recommendId) {
        return self::getDao()->queryAll(array('recommendId' => $recommendId), 'id desc');
    }

    public static function ByTopDesc($top, $desc) {
        return self::getDao()->queryPage(array(), $desc, $top, 0);
    }

    public static function ByAll($userSearch) {
        return self::getDao()->queryAll($userSearch->getSearchFileds());
    }

    public function bindWeixin($weixinId) {
        $weixinItem = Application_Model_Weixin::getItemByWeixinIdUserId($weixinId, $this->_id);
        if (!$weixinItem) {
            return Application_Model_Weixin::addBindWeixin($weixinId, $this->_id);
        }
        return $weixinItem->Id;
    }

}
